package config

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/tools"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
)

// SaveConfig 保存配置数据
func (c *sConfig) SaveConfig(ctx context.Context, params ...entity.Config) error {
	// 处理数据
	handler, err := c.saveConfigHandler(ctx, params)
	if err != nil {
		return err
	}

	// 保存配置数据
	err = dao.Config.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		_, err = tx.Save(dao.Config.Table(), handler.SaveAll)
		return err
	})
	if err != nil {
		return gerror.Wrapf(err, `保存配置失败%s`, err.Error())
	}
	// 清除缓存
	c.RemoveConfigCache(ctx, handler.Keys...)
	return nil
}

// RemoveConfigCache 清除配置缓存
func (c *sConfig) RemoveConfigCache(ctx context.Context, keys ...string) {
	if len(keys) == 0 {
		return
	}
	// 处理配置
	cache := sredis.NewCache()
	for _, v := range keys {
		// 删除配置
		_, _ = cache.Remove(ctx, tools.CacheKey(consts.SysConfigKey, v))
	}
}

// saveConfigHandler 添加编辑配置处理
func (c *sConfig) saveConfigHandler(ctx context.Context, params []entity.Config) (*model.ConfigSaveHandlerItem, error) {
	var (
		names, groupIdArr = make([]string, 0, len(params)), make([]uint, 0, len(params))
		uniMap            = make(map[string]bool)
		handler           = &model.ConfigSaveHandlerItem{}
	)
	if len(params) == 0 {
		return nil, gerror.New(`缺少配置数据`)
	}

	// 迭代处理配置名，配置组名，配置组ID
	for _, item := range params {
		names = append(names, item.Name)
		groupIdArr = append(groupIdArr, item.GroupId)
	}

	// 获取配置组名称
	groupNameMap, err := c.ProcessGroupGroupNameById(ctx, groupIdArr...)
	if err != nil {
		return nil, err
	}

	// 获取配置ID
	detailMap, _ := c.ProcessConfigDetailMapByName(ctx, names)

	// 迭代配置
	for _, item := range params {
		// 配置组
		if groupName, ok := groupNameMap[item.GroupId]; ok {
			item.GroupName = groupName
		}
		// 配置ID
		if detail, ok := detailMap[item.Name]; ok {
			item.Id = detail.Id
		}
		handler.SaveAll = append(handler.SaveAll, item)
		// 记录KEY-配置组
		if _, ok := uniMap[item.GroupName]; !ok {
			handler.Keys = append(handler.Keys, item.GroupName)
			uniMap[item.GroupName] = true
		}
		// 配置组-配置名拼接KEY
		handler.Keys = append(handler.Keys, item.GroupName+`-`+item.Name, item.Name)
	}
	return handler, nil
}
